Popular Searches
Popular Course Categories
Popular Courses

Working with Arrays, Sets, and Dictionaries

Working with Arrays, Sets, and Dictionaries

Swift Programming Fundamentals for iOS

Working with Arrays, Sets, and Dictionaries in Swift

Course: iOS App Development Training

Topic: Working with Arrays, Sets, and Dictionaries in Swift

Course Link: iOS App Development Training at JustAcademy

Demo Link: Register for a Free Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Collections in Swift

Collections are data structures used to store and organize multiple values in a single variable or constant. In Swift, the three fundamental collection types are Array, Set, and Dictionary. They help developers manage lists of data, eliminate duplicate values, and associate values with unique keys.

For example, an iOS application may use an array to display a list of products, a set to store unique category names, and a dictionary to keep user profile information as key-value pairs.

Learning Objectives

  • Understand the purpose of arrays, sets, and dictionaries in Swift.
  • Create mutable and immutable collections.
  • Insert, access, update, and remove collection elements.
  • Use loops and collection methods to process data.
  • Understand uniqueness, ordering, keys, and values.
  • Apply collections in practical iOS application scenarios.

2. Overview of Swift Collection Types

Feature Array Set Dictionary
Stores Ordered sequence of values Unique values Key-value pairs
Duplicates Allowed Not allowed Keys must be unique
Access method Index Membership or iteration Key
Order Maintains element order No guaranteed iteration order No guaranteed iteration order
Typical use Lists, tasks, products Unique tags, selected categories Profiles, settings, lookups

3. Working with Arrays

3.1 What Is an Array?

An array is an ordered collection that stores multiple values of the same element type. Each element has an index, beginning at zero. Arrays are useful when the position and order of values matter.

3.2 Creating Arrays

import Foundation

let fruits: [String] = ["Apple", "Banana", "Orange"]
let scores: [Int] = [85, 90, 78]
let emptyNames: [String] = []
var cities = ["Mumbai", "Pune", "Delhi"]

The type annotation [String] indicates an array of strings, while [Int] indicates an array of integers. Swift can often infer the type from the supplied values.

3.3 Accessing Array Elements

let fruits = ["Apple", "Banana", "Orange"]

print(fruits[0]) // Apple
print(fruits[1]) // Banana
print(fruits[2]) // Orange

print(fruits.count) // 3
print(fruits.isEmpty) // false

Array indexing starts at zero. Accessing an index outside the valid range causes a runtime error, so verify the index before accessing an element.

let index = 1

if fruits.indices.contains(index) {
    print(fruits[index])
}

3.4 Adding Elements to an Array

Declare an array with var when its contents need to change. Use append() to add one element at the end and insert(_:at:) to add an element at a specific valid index.

var tasks = ["Study Swift", "Practice Xcode"]

tasks.append("Build an iOS App")
tasks.insert("Read Documentation", at: 0)

print(tasks)
// ["Read Documentation", "Study Swift", "Practice Xcode", "Build an iOS App"]

To add several elements together, use append(contentsOf:).

var numbers = [1, 2, 3]
numbers.append(contentsOf: [4, 5, 6])

print(numbers) // [1, 2, 3, 4, 5, 6]

3.5 Updating Array Elements

var prices = [100, 200, 300]
prices[1] = 250

print(prices) // [100, 250, 300]

An existing element can be changed by assigning a new value to its index. The new value must match the array's element type.

3.6 Removing Array Elements

var languages = ["Swift", "Java", "Python", "Kotlin"]

languages.remove(at: 1)
print(languages) // ["Swift", "Python", "Kotlin"]

languages.removeFirst()
print(languages) // ["Python", "Kotlin"]

languages.removeLast()
print(languages) // ["Python"]

languages.removeAll()
print(languages) // []

Use remove(at:) only with a valid index. Use removeAll(where:) when removing elements that match a condition.

var numbers = [1, 2, 3, 4, 5, 6]
numbers.removeAll { $0.isMultiple(of: 2) }

print(numbers) // [1, 3, 5]

3.7 Searching and Checking Array Values

let names = ["Aarav", "Meera", "Riya", "Meera"]

print(names.contains("Riya")) // true
print(names.firstIndex(of: "Meera") as Any) // Optional(1)
print(names.first as Any) // Optional("Aarav")
print(names.last as Any) // Optional("Meera")

contains() checks whether a value exists. firstIndex(of:) returns the first matching index as an optional value because the element might not exist.

3.8 Sorting and Reversing Arrays

var scores = [72, 95, 68, 88]

scores.sort()
print(scores) // [68, 72, 88, 95]

scores.sort(by: >)
print(scores) // [95, 88, 72, 68]

let reversedScores = scores.reversed()
print(Array(reversedScores)) // [68, 72, 88, 95]

sort() modifies a mutable array. sorted() returns a sorted array without modifying the original collection.

let values = [5, 2, 8, 1]
let sortedValues = values.sorted()

print(sortedValues) // [1, 2, 5, 8]
print(values) // [5, 2, 8, 1]

3.9 Iterating Through an Array

let subjects = ["Swift", "UIKit", "SwiftUI"]

for subject in subjects {
    print(subject)
}

for (index, subject) in subjects.enumerated() {
    print("\(index): \(subject)")
}

Use a standard for-in loop when you need each value. Use enumerated() when both the position and value are required.

3.10 Useful Array Operations

let numbers = [10, 20, 30, 40, 50]

let doubled = numbers.map { $0 * 2 }
let greaterThan25 = numbers.filter { $0 > 25 }
let total = numbers.reduce(0, +)

print(doubled) // [20, 40, 60, 80, 100]
print(greaterThan25) // [30, 40, 50]
print(total) // 150
  • map() transforms each element and creates a new array.
  • filter() selects elements that satisfy a condition.
  • reduce() combines the elements into one result.
  • compactMap() transforms values and removes nil results.
  • flatMap() can flatten nested sequences or transform elements into sequences.

4. Working with Sets

4.1 What Is a Set?

A set is an unordered collection of unique values of the same type. Duplicate values are not stored as separate elements. Sets are particularly useful for checking membership and removing duplicates.

4.2 Creating a Set

let programmingLanguages: Set<String> = [
    "Swift", "Python", "Java"
]

var selectedCategories: Set<String> = [
    "Technology", "Education"
]

let emptyIDs = Set<Int>()

Swift uses the explicit Set<Type> syntax to declare a set. Curly braces are not used for set literals; square brackets are used, as with array literals, so the declared type distinguishes the collection.

4.3 Understanding Unique Values

let numbers: Set<Int> = [1, 2, 2, 3, 3, 4]

print(numbers.count) // 4
print(numbers.contains(3)) // true

Only unique values remain in the set. Because sets do not guarantee a particular iteration order, do not depend on the printed order of their elements.

4.4 Adding and Removing Set Elements

var skills: Set<String> = ["Swift", "Git"]

skills.insert("SwiftUI")
skills.insert("Swift") // Already exists

print(skills.count) // 3

skills.remove("Git")
print(skills.contains("Git")) // false

The insert() method adds a value only if it is not already present. The remove() method returns an optional value, which is nil when the element was not present.

if let removedSkill = skills.remove("SwiftUI") {
    print("Removed: \(removedSkill)")
}

4.5 Iterating Through a Set

let devices: Set<String> = ["iPhone", "iPad", "Mac"]

for device in devices {
    print(device)
}

// Sort the values when predictable display order is needed.
for device in devices.sorted() {
    print(device)
}

Use sorted() to produce an ordered array for consistent display. Sorting requires the element type to support the chosen comparison.

4.6 Set Operations

Swift sets support mathematical operations that compare two collections of unique values.

let iosSkills: Set<String> = ["Swift", "SwiftUI", "Xcode"]
let sharedSkills: Set<String> = ["Swift", "Git", "Xcode"]

let unionSkills = iosSkills.union(sharedSkills)
let commonSkills = iosSkills.intersection(sharedSkills)
let exclusiveSkills = iosSkills.symmetricDifference(sharedSkills)
let onlyIOSSkills = iosSkills.subtracting(sharedSkills)

print(unionSkills)
print(commonSkills) // Swift and Xcode
print(exclusiveSkills)
print(onlyIOSSkills) // SwiftUI
Operation Purpose Example
union() Combines elements from both sets, without duplicates. A ∪ B
intersection() Returns elements present in both sets. A ∩ B
subtracting() Returns elements in the first set but not the second. A − B
symmetricDifference() Returns elements belonging to exactly one of the sets. A △ B

4.7 Checking Set Relationships

let frontend: Set<String> = ["HTML", "CSS"]
let webSkills: Set<String> = ["HTML", "CSS", "JavaScript"]

print(frontend.isSubset(of: webSkills)) // true
print(webSkills.isSuperset(of: frontend)) // true
print(frontend.isDisjoint(with: Set(["Swift", "Kotlin"]))) // true
  • isSubset(of:) checks whether every element in one set exists in another.
  • isSuperset(of:) checks whether a set contains every element of another set.
  • isDisjoint(with:) checks whether two sets have no elements in common.
  • == checks whether two sets contain the same elements, regardless of order.

5. Working with Dictionaries

5.1 What Is a Dictionary?

A dictionary stores values as key-value pairs. Each key must be unique and conforms to Swift's Hashable requirements. Keys are used to retrieve, insert, update, or remove associated values.

For example, a user profile might store a person's name, city, and age. A product catalog might associate product IDs with product names.

5.2 Creating Dictionaries

let studentMarks: [String: Int] = [
    "Aarav": 85,
    "Meera": 92,
    "Riya": 88
]

var userProfile: [String: String] = [
    "name": "Aarav",
    "city": "Mumbai"
]

let emptyDictionary: [String: Int] = [:]

The dictionary type [String: Int] means the keys are strings and the values are integers. Keys and values can use different types, as long as the key type conforms to Hashable.

5.3 Accessing Dictionary Values

let employee = [
    "name": "Priya",
    "department": "Engineering"
]

print(employee["name"] as Any) // Optional("Priya")
print(employee["department"] as Any) // Optional("Engineering")
print(employee["salary"] as Any) // nil

Dictionary subscripting returns an optional value because the requested key may not exist. Safely unwrap the result before using it as a definite value.

if let department = employee["department"] {
    print("Department: \(department)")
} else {
    print("Department not found")
}

5.4 Adding and Updating Dictionary Values

var productPrices: [String: Double] = [
    "Phone": 49999,
    "Tablet": 29999
]

productPrices["Laptop"] = 64999
productPrices["Phone"] = 51999

print(productPrices["Laptop"] as Any)
print(productPrices["Phone"] as Any)

Assigning a value to a new key inserts a new entry. Assigning a value to an existing key updates its associated value.

You can also use updateValue(_:forKey:), which returns the previous value as an optional.

let oldPrice = productPrices.updateValue(52999, forKey: "Phone")
print(oldPrice as Any) // Optional(51999)

5.5 Removing Dictionary Entries

var settings: [String: String] = [
    "theme": "dark",
    "language": "English",
    "fontSize": "medium"
]

settings["fontSize"] = nil
settings.removeValue(forKey: "language")

print(settings)

Setting a dictionary value to nil removes that key-value pair. The removeValue(forKey:) method also returns the removed value as an optional.

To remove every entry while retaining the dictionary variable, use:

settings.removeAll()
print(settings.isEmpty) // true

5.6 Iterating Through Dictionaries

let user = [
    "name": "Meera",
    "city": "Pune",
    "role": "Developer"
]

for (key, value) in user {
    print("\(key): \(value)")
}

for key in user.keys {
    print(key)
}

for value in user.values {
    print(value)
}

Dictionary iteration order is not guaranteed. Sort keys when the interface requires a predictable display order.

for key in user.keys.sorted() {
    if let value = user[key] {
        print("\(key): \(value)")
    }
}

5.7 Checking Dictionary Contents

let inventory = [
    "iPhone": 10,
    "iPad": 5,
    "MacBook": 3
]

print(inventory.isEmpty) // false
print(inventory.count) // 3
print(inventory.keys.contains("iPhone")) // true
print(inventory["iPad"] ?? 0) // 5
print(inventory["Apple Watch"] ?? 0) // 0

The nil-coalescing operator ?? provides a fallback value when a dictionary lookup returns nil. Choose a fallback that makes sense for the application rather than assuming every missing value means zero.

6. Mutability: let and var

Swift distinguishes between constants and variables. Use let when a collection should not be reassigned or mutated, and var when its contents need to change.

let fixedNumbers = [1, 2, 3]
// fixedNumbers.append(4) // Compile-time error

var editableNumbers = [1, 2, 3]
editableNumbers.append(4)

print(editableNumbers) // [1, 2, 3, 4]

Arrays, sets, and dictionaries are value types. Assigning one collection to another creates an independent value; changing the variable copy does not change the original collection.

var original = [10, 20, 30]
var copied = original

copied.append(40)

print(original) // [10, 20, 30]
print(copied) // [10, 20, 30, 40]

7. Choosing the Right Collection

Requirement Recommended Type Reason
Display ordered products Array Preserves element order and supports index access.
Store unique user-selected tags Set Prevents duplicate values.
Look up a product using its ID Dictionary Associates a key with a value.
Store recent search terms in order Array Supports sequence-based processing.
Find common permissions between roles Set Provides intersection and related operations.
Store app settings by name Dictionary Allows values to be retrieved using keys.

8. Combining Arrays, Sets, and Dictionaries

Real iOS applications often use more than one collection type. For example, an application can display an ordered list of categories, use a set to track selected categories, and use a dictionary to store the number of products in each category.

let categories = ["Electronics", "Books", "Clothing"]

var selectedCategories: Set<String> = [
    "Books", "Electronics"
]

let productCounts: [String: Int] = [
    "Electronics": 12,
    "Books": 20,
    "Clothing": 8
]

for category in categories {
    let selected = selectedCategories.contains(category)
    let count = productCounts[category] ?? 0

    print("\(category): \(count) products, selected: \(selected)")
}

This example uses an array to maintain the display order, a set to check membership efficiently, and a dictionary to retrieve a count by category name.

9. Practical iOS Example: Managing a Shopping List

The following example demonstrates how an array can maintain the shopping list order, a set can track completed items, and a dictionary can store item prices.

import Foundation

var shoppingList = ["Milk", "Bread", "Apples"]

var completedItems: Set<String> = ["Bread"]

var itemPrices: [String: Double] = [
    "Milk": 2.50,
    "Bread": 1.75,
    "Apples": 3.00
]

for item in shoppingList {
    let status = completedItems.contains(item) ? "Completed" : "Pending"
    let price = itemPrices[item] ?? 0.0

    print("\(item) - \(status) - $\(price)")
}

// Add a new item
shoppingList.append("Eggs")
itemPrices["Eggs"] = 4.25

// Mark an item as completed
completedItems.insert("Milk")

// Remove an item from the list
if let index = shoppingList.firstIndex(of: "Apples") {
    shoppingList.remove(at: index)
}

print("Shopping list: \(shoppingList)")
print("Completed items: \(completedItems)")

How the Example Works

  1. Array: Stores the shopping items in the order they should appear.
  2. Set: Tracks completed items without allowing duplicates.
  3. Dictionary: Maps each item name to its price.
  4. Loop: Displays each item's status and price.
  5. Mutation: Adds items, updates completion status, and removes an item.

For a production application, consider using a model type such as a struct ShoppingItem when each item needs additional properties like a unique ID, quantity, category, and completion state.

10. Common Errors and Best Practices

Problem Cause Best Practice
Array index out of range Accessing an invalid index Check indices or use safe search results.
Unexpected duplicate values Using an array where uniqueness is required Consider a set when order and duplicates are unnecessary.
Dictionary lookup returns nil The key does not exist Use optional binding or an appropriate fallback.
Unexpected display order Assuming sets or dictionaries have a stable iteration order Sort values or keys before displaying them.
Cannot modify a collection The collection was declared with let Use var when mutation is required.
Duplicate dictionary key in source literal Repeated keys are provided in a literal Ensure literal keys are unique and update existing values intentionally.
Collection type mismatch Inserting a value of the wrong type Use the declared element, key, and value types.

Performance Considerations

  • Array index access is typically constant time, while searching for an arbitrary value is generally linear.
  • Set membership and dictionary key lookup are typically expected constant time, though performance depends on hashing and collisions.
  • Appending to an array is typically amortized constant time, but may occasionally require reallocating storage.
  • Choose a collection based on the operations your application performs most often.
  • Avoid repeatedly sorting collections when a single sorted result can be reused.
  • Do not rely on collection ordering unless the collection type guarantees it.

11. Practice Exercises

  1. Array Exercise: Create an array of ten integers. Print the smallest number, largest number, and total of all values.
  2. Array Filtering: Create an array of student marks and filter out marks below 40.
  3. Set Exercise: Create two sets of programming languages. Display their union, intersection, and difference.
  4. Duplicate Removal: Convert an array with repeated strings into a set and compare the number of elements before and after conversion.
  5. Dictionary Exercise: Create a dictionary of product names and prices. Add a product, update a price, and remove an entry.
  6. Combined Exercise: Maintain an ordered list of tasks, a set of completed task names, and a dictionary of task priorities.

12. Mini Project: Student Result Manager

Objective: Build a small Swift program that stores student names and marks, tracks unique subjects, and calculates the class average.

import Foundation

let studentMarks: [String: Int] = [
    "Aarav": 85,
    "Meera": 92,
    "Riya": 78,
    "Kabir": 88
]

let subjects: Set<String> = [
    "Swift", "iOS Development", "SwiftUI"
]

let orderedStudents = studentMarks.keys.sorted()

for name in orderedStudents {
    if let marks = studentMarks[name] {
        let result = marks >= 40 ? "Pass" : "Fail"
        print("\(name): \(marks) - \(result)")
    }
}

let totalMarks = studentMarks.values.reduce(0, +)
let studentCount = studentMarks.count

if studentCount > 0 {
    let average = Double(totalMarks) / Double(studentCount)
    print("Class average: \(average)")
}

print("Subjects offered: \(subjects.sorted())")

Project Requirements

  • Store student marks in a dictionary.
  • Store unique subject names in a set.
  • Sort student names for consistent output.
  • Calculate the class average using reduce().
  • Display pass or fail status for each student.
  • Extend the project to find the highest mark and add new students.

13. Interview Questions and Answers

Q1. What is an array in Swift?

An array is an ordered collection of values of the same type. It supports index-based access and can contain duplicate values.

Q2. What is the difference between an array and a set?

An array preserves element order and allows duplicates. A set stores unique values and does not guarantee iteration order.

Q3. How do you create an empty array?

var names: [String] = []
// Alternative:
var scores = [Int]()

Q4. How do you add an element to an array?

Use append() to add an element at the end, or insert(_:at:) to insert an element at a specific valid index.

Q5. Why does dictionary lookup return an optional?

The requested key might not exist. Returning an optional lets Swift represent either a found value or nil.

Q6. How do you remove duplicate values from a collection?

When order does not matter, convert the values to a set. If the original order must be preserved, use a separate tracking set while building a new array.

let input = ["Swift", "Java", "Swift", "Python"]
var seen: Set<String> = []
let uniqueInOrder = input.filter { seen.insert($0).inserted }

print(uniqueInOrder) // ["Swift", "Java", "Python"]

Q7. What is the difference between sort() and sorted()?

sort() changes a mutable collection in place. sorted() returns a new sorted array and leaves the original collection unchanged.

Q8. What is the purpose of map(), filter(), and reduce()?

map() transforms values, filter() selects values matching a condition, and reduce() combines values into a single result.

Q9. Can a dictionary contain duplicate keys?

No. Each key must be unique. Assigning a value to an existing key updates the associated value.

Q10. When should a dictionary be preferred over an array?

Use a dictionary when values need to be retrieved by a unique key rather than by their position in an ordered sequence.

14. Quick Revision Checklist

  • Understand the differences between arrays, sets, and dictionaries.
  • Use let for collections that should not change and var for mutable collections.
  • Remember that array indices start at zero.
  • Use set operations to compare unique values.
  • Handle dictionary lookups safely because they return optional values.
  • Use map(), filter(), and reduce() to process data.
  • Sort set values or dictionary keys when a predictable display order is required.
  • Practice combining collection types in small Swift projects.

15. Conclusion

Arrays, sets, and dictionaries are essential building blocks in Swift and native iOS development. Arrays are ideal for ordered sequences, sets are useful for unique values and membership checks, and dictionaries provide efficient key-based access to associated values. Understanding how to create, update, search, iterate over, and transform these collections helps you write safer and more maintainable Swift code.

Continue practicing these concepts by building lists, search features, settings screens, product catalogs, and other small iOS application components.

16. Learning Resources

Previous Next
whatsapp